const {sequelize} = require('../cors/db')
const {Sequelize,Model,Op} = require('sequelize')
const {Favor} = require('./favor')

class HotBook extends Model{
    static async getAll(){
        const books =await HotBook.findAll({
            order:[
                'index'
            ]//查询所有根据index 排序
        })
        const ids = []
        books.forEach((book)=>{
            ids.push(book.id)
        })
        const favors =await Favor.findAll({
            where:{
                art_id:{
                    [Op.in]:ids,
                   
                },
                type:400
                // 国画
                // 漫画
            },
            group:['art_id'],//分组
            attributes:['art_id', [Sequelize.fn('COUNT','*'),'count']]//attributes 分组后要包含哪些字段Sequelize.fn('COUNT','*')求和的意思 fn有很多帮助函数记录的总数量Sum//, [Sequelize.fn('COUNT','*'),'count']]数量的名字
        })
        // 数据接口 [{art_id:11,count:1}]
        books.forEach(book=>{
             HotBook._getEachBookStatus(book, favors)
        })
        //python 二维矩阵
        return books
    }

    static _getEachBookStatus(book, favors){
        let count = 0
        favors.forEach(favor=>{
            if(book.id === favor.art_id){
                count = favor.get('count') //获取favor的count
            }
        })
        book.setDataValue('count',count)//保存在book里面
        return book
    }
}

HotBook.init({
    index: Sequelize.INTEGER,
    image: Sequelize.STRING,
    author: Sequelize.STRING,
    title: Sequelize.STRING
},{
    sequelize,
    tableName:'hot_book'
})

module.exports = {
    HotBook
}
// 排序 重要